package com.android.jay.lib_audio.mediaplayer.core;

import com.android.jay.lib_audio.mediaplayer.db.GreenDaoHelper;
import com.android.jay.lib_audio.mediaplayer.event.AudioFavouriteEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioPlayModeEvent;
import com.android.jay.lib_audio.mediaplayer.exception.AudioQueueEmptyException;
import com.android.jay.lib_audio.mediaplayer.model.AudioBean;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Random;

/**
 * Created by wzp on 2020/1/14 0014.
 * <p>
 * 描述  ：控制播放逻辑类
 */
public class AudioController {


    public enum PlayMode {

        /**
         * 列表循环
         **/
        LOOP,
        /**
         * 随机
         **/
        RANDOM,
        /**
         * 单曲循环
         **/
        REPEAT
    }


    /**
     * 单例方法
     **/
    public static AudioController getInstance() {
        return AudioController.SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static AudioController instance = new AudioController();
    }

    private AudioPlayer mAudioPlayer; //核心播放器
    private ArrayList<AudioBean> mQueue; // 歌曲队列
    private PlayMode mPlayMode; //播放模式
    private int mQueueIndex;   //当前播放索引

    private AudioController() {
        mAudioPlayer = new AudioPlayer();
        mQueue = new ArrayList<>();
        mQueueIndex = 0;
        mPlayMode = PlayMode.LOOP;
    }

    //
    public ArrayList<AudioBean> getQueue() {
        return mQueue == null ? new ArrayList<AudioBean>() : mQueue;
    }

    //设置播放队列
    public void setQueue(ArrayList<AudioBean> queue) {
        this.setQueue(queue, 0);
    }

    /**
     * 设置有下标的播放队列
     **/

    public void setQueue(ArrayList<AudioBean> queue, int index) {
        mQueue.addAll(queue);
        this.mQueueIndex = index;
    }

    /**
     * 只添加一首歌曲
     **/

    public void addAudio(AudioBean bean) {
        this.addAudio(0, bean);
    }

    public void addAudio(int index, AudioBean bean) {
        if (mQueue == null) {
            throw new AudioQueueEmptyException("当前播放队列为空");
        }
        //先判断添加的音乐是否已经存在了
        int query = queryAudio(bean);
        if (query <= -1) {
            // 没有添加过
            addCustomAudio(index, bean);
            //添加并播放
            setPlayIndex(index);
        } else {
            //
            AudioBean currentbean = getNowPlaying();
            if (!bean.getId().equals(currentbean.getId())) {
                //已经添加了 且在不在播放中了
                setPlayIndex(query);
            }
        }
    }

    private void addCustomAudio(int index, AudioBean bean) {
        if (mQueue == null) {
            throw new AudioQueueEmptyException("当前播放队列为空,请先设置播放队列.");
        }
        mQueue.add(index, bean);
    }

    private int queryAudio(AudioBean bean) {

        return mQueue.indexOf(bean);
    }

    /**
     * 获取播放模式
     **/
    public PlayMode getPlayMode() {
        return mPlayMode;
    }

    /**
     * 对外提供设置播放状态
     **/
    public void setPlayMode(PlayMode mode) {
        this.mPlayMode = mode;
        EventBus.getDefault().post(new AudioPlayModeEvent(mode));
    }

    /**
     * 设置播放的index
     **/
    public void setPlayIndex(int index) {
        if (mQueue == null) {
            throw new AudioQueueEmptyException("当前播放队列为空,请先设置播放队列.");
        }
        mQueueIndex = index;
        play();
    }

    public AudioBean getNowPlaying() {
        return getPlaying(mQueueIndex);
    }

    private AudioBean getNextPlaying() {
        switch (mPlayMode) {
            case LOOP:
                //防止数组越界
                mQueueIndex = (mQueueIndex + 1) % mQueue.size();
                break;
            case RANDOM:
                mQueueIndex = new Random().nextInt(mQueue.size()) % mQueue.size();
                break;
            case REPEAT:
                break;
        }
        return getPlaying(mQueueIndex);
    }

    private AudioBean getPrePlaying() {
        switch (mPlayMode) {
            case LOOP:
                //防止数组越界
                if (mQueueIndex == 0) {
                    //防止歌单第一首歌后退导致报错的问题
                    mQueueIndex = mQueue.size() - 1;
                } else {
                    mQueueIndex = (mQueueIndex - 1) % mQueue.size();
                }
                break;
            case RANDOM:
                mQueueIndex = new Random().nextInt(mQueue.size()) % mQueue.size();
                break;
            case REPEAT:
                break;
        }
        return getPlaying(mQueueIndex);
    }

    private AudioBean getPlaying(int index) {
        if (mQueue != null && !mQueue.isEmpty() && index >= 0 && index < mQueue.size()) {
            return mQueue.get(index);
        } else {
            throw new AudioQueueEmptyException("当前播放队列为空,请先设置播放队列.");
        }
    }


    /**
     * 对外提供的play方法
     **/
    public void play() {
        AudioBean bean = getNowPlaying();
        mAudioPlayer.load(bean);
    }

    public void pause() {
        mAudioPlayer.pause();

    }

    public void resume() {
        mAudioPlayer.resume();
    }

    public void release() {
        mAudioPlayer.release();
        EventBus.getDefault().unregister(this);
    }

    public void setMusicePostion(int time){
        mAudioPlayer.setMusicCurrentTime(time);
    }

    /**
     * 播放下一首
     **/

    public void next() {
        AudioBean bean = getNextPlaying();
        mAudioPlayer.load(bean);
    }

    /**
     * 播放上一首
     **/

    public void previous() {
        AudioBean bean = getPrePlaying();
        mAudioPlayer.load(bean);
    }

    /**
     * 自动切换播放暂停
     **/
    public void playOrPause() {
        if (isStartState()) {
            pause();
        } else if (isPauseState()) {
            resume();
        }
    }

    /**
     * 获取当前播放队列的下标
     **/
    public int getPlayIndex() {
        return mQueueIndex;
    }

    /**
     * 对外提供是否播放状态
     **/

    public boolean isStartState() {
        return CustomMediaPlayer.Status.STARTED == getStatus();
    }

    /**
     * 对外提供是否是暂停状态
     **/
    public boolean isPauseState() {
        return CustomMediaPlayer.Status.PAUSE == getStatus();
    }

    public void changeFavouriteState() {
        if (null != GreenDaoHelper.selectFavourite(getNowPlaying())) {
            //取消收藏
            GreenDaoHelper.removeFavourite(getNowPlaying());
            EventBus.getDefault().post(new AudioFavouriteEvent(false));
        } else {
            GreenDaoHelper.addFavourite(getNowPlaying());
            EventBus.getDefault().post(new AudioFavouriteEvent(true));
        }


    }


    private CustomMediaPlayer.Status getStatus() {
        return mAudioPlayer.getStatus();
    }


}
